<template>
    <div class="register-container">
        <div class="register-box">
            <div class="register-card">
                <div class="title-container">
                    <h3 class="title">学术活动及科研成果管理系统</h3>
                </div>

                <div class="register-content">
                    <el-steps :active="active" process-status="process" finish-status="wait" simple
                        class="register-steps">
                        <el-step title="基本信息"></el-step>
                        <el-step title="账号信息"></el-step>
                    </el-steps>

                    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form"
                        label-width="0px" autocomplete="off">
                        <!-- 第一步：基本信息 -->
                        <div v-show="active === 0" class="step-content">
                            <el-form-item prop="username">
                                <span class="svg-container">
                                    <svg-icon icon-class="user" />
                                </span>
                                <el-input v-model="registerForm.username" placeholder="用户名" autocomplete="off" />
                            </el-form-item>

                            <el-form-item prop="phone">
                                <span class="svg-container">
                                    <svg-icon icon-class="user" />
                                </span>
                                <el-input v-model="registerForm.phone" placeholder="手机号" autocomplete="off" />
                            </el-form-item>

                            <el-form-item prop="gender" class="gender-item">
                                <span class="label">性别：</span>
                                <el-radio-group v-model="registerForm.gender">
                                    <el-radio :label="1">男</el-radio>
                                    <el-radio :label="2">女</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item prop="roleId" class="role-item">
                                <span class="label">角色：</span>
                                <el-select v-model="registerForm.roleId" placeholder="请选择角色" @change="onRoleChange">
                                    <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </div>

                        <!-- 第二步：账号信息 -->
                        <div v-show="active === 1" class="step-content">
                            <!-- 只有学生需要填写学院和专业 -->
                            <el-form-item v-if="isStudent" prop="department">
                                <span class="svg-container">
                                    <svg-icon icon-class="user" />
                                </span>
                                <el-input v-model="registerForm.department" placeholder="所属学院" autocomplete="off" />
                            </el-form-item>

                            <el-form-item v-if="isStudent" prop="major">
                                <span class="svg-container">
                                    <svg-icon icon-class="user" />
                                </span>
                                <el-input v-model="registerForm.major" placeholder="专业" autocomplete="off" />
                            </el-form-item>

                            <el-form-item prop="account">
                                <span class="svg-container">
                                    <svg-icon icon-class="user" />
                                </span>
                                <el-input v-model="registerForm.account" placeholder="账号" autocomplete="off" />
                            </el-form-item>

                            <el-form-item prop="password">
                                <span class="svg-container">
                                    <svg-icon icon-class="password" />
                                </span>
                                <el-input :key="passwordType" ref="password" v-model="registerForm.password"
                                    :type="passwordType" placeholder="密码" autocomplete="new-password" />
                                <span class="show-pwd" @click="showPwd">
                                    <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                                </span>
                            </el-form-item>

                            <el-form-item prop="confirmPassword">
                                <span class="svg-container">
                                    <svg-icon icon-class="password" />
                                </span>
                                <el-input :key="confirmPasswordType" ref="confirmPassword"
                                    v-model="registerForm.confirmPassword" :type="confirmPasswordType"
                                    placeholder="确认密码" autocomplete="new-password" />
                                <span class="show-pwd" @click="showConfirmPwd">
                                    <svg-icon :icon-class="confirmPasswordType === 'password' ? 'eye' : 'eye-open'" />
                                </span>
                            </el-form-item>
                        </div>
                    </el-form>
                </div>

                <!-- 按钮区域 -->
                <div class="step-buttons">
                    <el-button v-if="active > 0" @click="prev">上一步</el-button>
                    <el-button v-if="active < 1" type="primary" @click="next">下一步</el-button>
                    <el-button v-if="active === 1" :loading="loading" type="primary"
                        @click.native.prevent="handleRegister">
                        提交注册
                    </el-button>
                </div>

                <div class="login-link">
                    <span>已有账号？</span>
                    <router-link to="/login">返回登录</router-link>
                </div>
            </div>
        </div>

        <div class="copyright">
            <span>@copyright 2003-2025 张子涵 陈兴瑶 期末作业版权所有</span>
        </div>
    </div>
</template>

<script>
import { validUsername, validEmail, validPhone } from '@/utils/validate'

export default {
    name: 'Register',
    data() {
        // 自定义验证规则
        const validateUsername = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入用户名'))
            } else if (value.length < 2 || value.length > 20) {
                callback(new Error('用户名长度应为2-20个字符'))
            } else {
                callback()
            }
        }
        const validateAccount = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入账号'))
            } else if (!validUsername(value)) {
                callback(new Error('账号格式不正确'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入密码'))
            } else if (value.length < 6 || value.length > 15) {
                callback(new Error('密码长度应为6-15个字符'))
            } else {
                if (this.registerForm.confirmPassword) {
                    this.$refs.registerForm.validateField('confirmPassword')
                }
                callback()
            }
        }
        const validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.registerForm.password) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        }
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号'))
            } else if (!validPhone(value)) {
                callback(new Error('手机号格式不正确'))
            } else {
                callback()
            }
        }
        const validateGender = (rule, value, callback) => {
            if (!value || value === 0) {
                callback(new Error('请选择性别'))
            } else {
                callback()
            }
        }
        const validateDepartment = (rule, value, callback) => {
            // 只有学生角色需要验证学院
            if (this.registerForm.roleId === '3') {
                if (!value) {
                    callback(new Error('请输入所属学院'))
                } else if (value.length < 2 || value.length > 50) {
                    callback(new Error('学院名称长度应为2-50个字符'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }
        const validateMajor = (rule, value, callback) => {
            // 只有学生角色需要验证专业
            if (this.registerForm.roleId === '3') {
                if (!value) {
                    callback(new Error('请输入专业'))
                } else if (value.length < 2 || value.length > 50) {
                    callback(new Error('专业名称长度应为2-50个字符'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }

        return {
            active: 0, // 当前步骤
            registerForm: {
                username: '',
                account: '',
                password: '',
                confirmPassword: '',
                phone: '',
                gender: 0,
                department: '',
                major: '',
                roleId: ''
            },
            registerRules: {
                username: [{ required: true, trigger: 'blur', validator: validateUsername }],
                account: [{ required: true, trigger: 'blur', validator: validateAccount }],
                password: [{ required: true, trigger: 'blur', validator: validatePassword }],
                confirmPassword: [{ required: true, trigger: 'blur', validator: validateConfirmPassword }],
                phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
                gender: [{ required: true, trigger: 'change', validator: validateGender }],
                department: [{ required: true, trigger: 'blur', validator: validateDepartment }],
                major: [{ required: true, trigger: 'blur', validator: validateMajor }],
                roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
            },
            passwordType: 'password',
            confirmPasswordType: 'password',
            loading: false,
            roleOptions: [
                { value: '1', label: '管理员' },
                { value: '2', label: '教师' },
                { value: '3', label: '学生' }
            ]
        }
    },
    computed: {
        // 判断是否为学生角色
        isStudent() {
            return this.registerForm.roleId === '3'
        }
    },
    created() {
        // 确保表单数据为空，防止浏览器自动填充
        this.resetFormData();
    },
    methods: {
        // 重置表单数据
        resetFormData() {
            this.registerForm = {
                username: '',
                account: '',
                password: '',
                confirmPassword: '',
                phone: '',
                gender: 0,
                department: '',
                major: '',
                roleId: ''
            };
            this.active = 0;
            // 清除表单验证状态
            this.$nextTick(() => {
                if (this.$refs.registerForm) {
                    this.$refs.registerForm.clearValidate();
                }
            });
        },

        // 角色变化处理
        onRoleChange(roleId) {
            // 如果不是学生角色，清空学院和专业信息
            if (roleId !== '3') {
                this.registerForm.department = ''
                this.registerForm.major = ''
                // 清除学院和专业字段的验证错误
                this.$nextTick(() => {
                    if (this.$refs.registerForm) {
                        this.$refs.registerForm.clearValidate(['department', 'major'])
                    }
                })
            }
        },

        // 下一步
        next() {
            // 根据当前步骤验证不同的表单项
            const fieldsToValidate = this.getFieldsToValidate();

            if (fieldsToValidate.length === 0) {
                this.active++;
                return;
            }

            // 验证当前步骤的所有字段
            let hasError = false;
            let validatedCount = 0;

            fieldsToValidate.forEach(field => {
                this.$refs.registerForm.validateField(field, (errorMsg) => {
                    validatedCount++;
                    if (errorMsg) {
                        hasError = true;
                    }

                    // 当所有字段都验证完成后
                    if (validatedCount === fieldsToValidate.length) {
                        if (!hasError) {
                            this.active++;
                            console.log('当前步骤:', this.active);
                        } else {
                            this.$message.error('请正确填写表单信息');
                        }
                    }
                });
            });
        },

        // 上一步
        prev() {
            if (this.active-- < 0) this.active = 0;
        },

        // 获取当前步骤需要验证的字段
        getFieldsToValidate() {
            switch (this.active) {
                case 0:
                    // 第一步：基本信息
                    return ['username', 'phone', 'gender', 'roleId'];
                case 1:
                    // 第二步：账号信息
                    const secondStepFields = ['account', 'password', 'confirmPassword'];
                    // 如果是学生角色，还需要验证学院和专业
                    if (this.registerForm.roleId === '3') {
                        secondStepFields.unshift('department', 'major');
                    }
                    return secondStepFields;
                default:
                    return [];
            }
        },

        showPwd() {
            if (this.passwordType === 'password') {
                this.passwordType = ''
            } else {
                this.passwordType = 'password'
            }
            this.$nextTick(() => {
                this.$refs.password.focus()
            })
        },

        showConfirmPwd() {
            if (this.confirmPasswordType === 'password') {
                this.confirmPasswordType = ''
            } else {
                this.confirmPasswordType = 'password'
            }
            this.$nextTick(() => {
                this.$refs.confirmPassword.focus()
            })
        },

        handleRegister() {
            this.$refs.registerForm.validate(async valid => {
                if (valid) {
                    this.loading = true
                    try {
                        // 构建注册数据
                        const registerData = {
                            username: this.registerForm.username,
                            account: this.registerForm.account,
                            password: this.registerForm.password,
                            phone: this.registerForm.phone,
                            gender: this.registerForm.gender,
                            department: this.registerForm.department || null,
                            major: this.registerForm.major || null,
                            roleId: this.registerForm.roleId
                        }
                        // 调用注册API
                        await this.$store.dispatch('user/register', registerData)
                        this.$message({
                            type: 'success',
                            message: '注册申请已提交，请等待管理员审核'
                        })

                        // 切换到登录页
                        this.$router.push('/login')
                    } catch (error) {
                        console.log(error);
                    } finally {
                        this.loading = false
                    }
                } else {
                    return false
                }
            })
        }
    }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
$cursor: #409EFF;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .register-container .el-input input {
        color: $cursor;
    }
}

/* reset element-ui css */
.register-container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

    .el-tabs__item {
        color: #606266;
        font-size: 16px;
        font-weight: 500;

        &.is-active {
            color: #409EFF;
        }
    }

    .el-tabs__nav-wrap::after {
        background-color: transparent;
    }

    .el-input {
        display: inline-block;
        height: 47px;
        width: 85%;

        input {
            background: transparent;
            border: 0px;
            -webkit-appearance: none;
            border-radius: 0px;
            padding: 12px 5px 12px 15px;
            color: #333;
            height: 47px;
            caret-color: $cursor;

            &:-webkit-autofill {
                transition: background-color 5000s ease-in-out 0s;
            }
        }
    }

    .el-form-item {
        border: 1px solid rgba(0, 0, 0, 0.1);
        background: rgba(255, 255, 255, 0.9);
        border-radius: 5px;
        margin-bottom: 35px;
        position: relative;
    }

    .el-form-item.is-error {
        border-color: #f56c6c;
    }

    .el-form-item__error {
        position: absolute;
        top: 100%;
        left: 15px;
        line-height: 1.2;
        padding-top: 6px;
        color: #f56c6c;
        font-size: 12px;
        z-index: 10;
        background: rgba(255, 255, 255, 0.95);
        padding: 4px 8px;
        border-radius: 3px;
        box-shadow: 0 2px 4px rgba(245, 108, 108, 0.2);
    }
}
</style>

<style lang="scss" scoped>
$dark_gray: #889aa4;
$light_gray: #333;

.register-container {
    min-height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .register-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100vh;
    }

    .register-card {
        width: 520px;
        max-height: 700px;
        min-height: 620px;
        padding: 30px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 10px;
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
        backdrop-filter: blur(10px);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .register-steps {
        margin-bottom: 20px;
        padding: 0 10px;

        ::v-deep .el-step__title {
            font-size: 14px;
            font-weight: 500;
        }

        ::v-deep .el-step__head.is-process {
            color: #409EFF;
            border-color: #409EFF;
        }

        ::v-deep .el-step__title.is-process {
            color: #409EFF;
        }
    }

    .register-content {
        flex: 1;
        overflow-y: auto;
        padding: 0 5px;
        margin-bottom: 10px;
        max-height: 460px;
        min-height: 360px;

        &::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        &::-webkit-scrollbar-thumb {
            background: #c0c4cc;
            border-radius: 3px;
        }

        &::-webkit-scrollbar-track {
            background: #f0f2f5;
            border-radius: 3px;
        }
    }

    .register-form {
        width: 100%;
        max-width: 100%;
    }

    .step-content {
        min-height: 320px;
        padding: 10px 0 20px 0;
    }

    .step-buttons {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
        padding: 0 5px;

        .el-button {
            width: 48%;
            border-radius: 20px;
            height: 40px;
            font-size: 15px;
        }

        .el-button:only-child {
            width: 100%;
        }
    }

    .login-link {
        text-align: center;
        margin-top: 10px;
        font-size: 14px;
        color: #606266;

        a {
            color: #409EFF;
            cursor: pointer;
            margin-left: 5px;
        }
    }

    .svg-container {
        padding: 6px 5px 6px 15px;
        color: $dark_gray;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
    }

    .title-container {
        position: relative;

        .title {
            font-size: 26px;
            color: $light_gray;
            margin: 0px auto 30px auto;
            text-align: center;
            font-weight: bold;
        }
    }

    .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        font-size: 16px;
        color: $dark_gray;
        cursor: pointer;
        user-select: none;
    }

    .label {
        padding: 6px 5px 6px 15px;
        color: $dark_gray;
        display: inline-block;
    }

    .gender-item,
    .role-item {
        display: flex;
        align-items: center;

        .label {
            flex-shrink: 0;
            margin: 0;
            padding: 6px 15px 6px 15px;
        }
    }

    .el-radio-group {
        flex: 1;
        margin-left: 15px;
    }

    .el-select {
        flex: 1;
        margin-left: 15px;
        max-width: calc(100% - 80px);
    }

    .copyright {
        position: absolute;
        bottom: 20px;
        width: 100%;
        font-size: 14px;
        text-align: center;
        color: rgba(255, 255, 255, 0.8);
    }
}
</style>
